package cn.elwy.rcp.ui.table.internal;

import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;

import cn.elwy.common.util.sort.SortUtil;
import cn.elwy.rcp.ui.table.provider.TablePaneLabelProvider;

public class ColumnSorter extends ViewerSorter {

  private IBaseLabelProvider labelProvider;

  // 排序的列索引
  private int columnIndex;
  // 是否升序
  private boolean isAscend;

  public ColumnSorter(IBaseLabelProvider labelProvider) {
    this.labelProvider = labelProvider;
  }

  public void setColumnIndex(int columnIndex) {
    if (columnIndex == this.columnIndex) {
      isAscend = !isAscend;
    } else {
      this.columnIndex = columnIndex;
      isAscend = false;
    }
  }

  public boolean isAscend() {
    return isAscend;
  }

  @Override
  public int compare(Viewer viewer, Object e1, Object e2) {
    Object value1 = e1;
    Object value2 = e2;
    if (labelProvider instanceof TablePaneLabelProvider) {
      value1 = ((TablePaneLabelProvider) labelProvider).getValue(e1, columnIndex);
      value2 = ((TablePaneLabelProvider) labelProvider).getValue(e2, columnIndex);
    }
    int result = SortUtil.compareTo(value1, value2);
    return isAscend ? result : -result;
  }
}